package com.baike.service.impl;

import com.baike.damian.FmLessonDTO;
import com.baike.data.Result;
import com.baike.feign.LessonServiceFeign;
import com.baike.service.FreemarkerService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:pjm
 */
@Service
public class FreemarkerServiceImpl implements FreemarkerService {
    //注入配置类
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Autowired
    private LessonServiceFeign lessonServiceFeign;

    @Override
    public void creatPage(Long lessonId) {
        //获取configration对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        FileWriter writer = null;
        try {
            //加载模板,创建模板对象
            Template template = configuration.getTemplate("text.ftl");
            //创建模板使用的数据集,可以是pojo,一般为map
            Map map = new HashMap();
//            FmLessonDTO lessonDTO = new FmLessonDTO();
//            lessonDTO.setLessonFree(1);
//            lessonDTO.setLessonIntroduce("课程介绍");
//            map.put("lessonIds",lessonDTO);
            //创建一个writer对象,一般创建一个FileWriter对象,指定生成文件名
            writer = new FileWriter("E:\\freemarker\\"+lessonId+".html");
            //数据填充,根据lessonId查询课程tb_lesson详细信息,调用接口
            Result<FmLessonDTO> result = lessonServiceFeign.selectByLessonId(lessonId);
            System.out.println(result.getCode());
            if (result.getCode().intValue() == 11000){//熔断了
                map.put("result",result);
            }
            FmLessonDTO lessonDTO = result.getResult();
            System.out.println(lessonDTO.toString());
            map.put("lessonDTO",lessonDTO);
            //调用模板对象的proess方法输出文件,生成页面
            template.process(map,writer);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关流
            if (writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
